/**
 * 全局缓存
 */

class Cache {
  constructor() {
    this.cache = {
      token: {}, // 小程序登录token
      schedule_job: {}, // 定时任务job
      applet: {}, // web登录token
      socket: {},
      email: {} //邮箱验证码
    }
  }
  /**
   * 添加缓存
   * @param {string} ns 命名空间
   * @param {string} key 键名 
   * @param {object} value 值
   * @param {number} time 过期时间/ms
   */
  setCache = function (ns, key, value, time) {
    const expire = time ? time : null
    const namespace = ns ? ns : 'token'
    this.cache[namespace][key] = value
    if (expire) {
      setTimeout(() => {
        delete this.cache[namespace][key]
      }, expire)
      this.cache[namespace][key]['expire'] = Date.now() + expire
    }
  }

  hasKey = function (namespace, key) {
    const data = this.cache[namespace]
    const keys = Object.keys(data)


    return keys.indexOf(key) > -1
  }

  /**
   * 查询缓存
   * @param {string} 命名空间 
   * @param {string} key 
   */
  getCache = function (namespace, key) {
    if (key) return this.cache[namespace][key]
    else {
      return ''
    }
  }

  /**
   * 删除缓存
   */
  delCache = function (namespace, key) {
    delete this.cache[namespace][key]
  }

  setData = (key, value) => {
    this.cache[key] = value
  }
}


let globalCache = new Cache()

export default globalCache
